/*
 * Copyright (c) 2006 Zsolt Szasz <zsolt at lorecraft dot com>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package org.lorecraft.rssappender;

import java.net.*;
import java.io.*;
import java.util.*;

import org.apache.log4j.helpers.LogLog;

public class BareHttpd {
	private boolean running;
	private Map handlers = new HashMap();
	private final int port;

	public BareHttpd(int port) {
		if (port <= 1023 || port > 65535) {
			throw new IllegalArgumentException("The port must be > 1023 and < 65536!");
		}
		this.port = port;
	}

	public void stop() {
		running = false;
	}

	public void start() {
		ServerSocket ss;
		try {
			ss = new ServerSocket(port);
			ss.setSoTimeout(1000);
		} catch (IOException e) {			
			LogLog.error("Exception setting up server socket, stopping server");
			return;
		}		
		running = true;
		try {
		while (running) {
			try {
				new BareHttpdConnection(ss.accept(), this);
			} catch (SocketTimeoutException e) {}
			catch (IOException e) {
				LogLog.error("Exception while accepting connection, shutting down");
				running = false;
			}
		}
		} finally {
			try {
				ss.close();
			} catch (IOException e) {
				// do nothing				
			}
		}
	}
	
	public void addHandler(String uri, Handler handler) {
		handlers.put(uri, handler);
	}

	public Handler getHandler(String req) {
		Handler handler = (Handler) handlers.get(req);
		return handler == null ? new DefaultHandler() : handler;
	}

}
